package net.xinqushi.pthread.pthreadPool;

import net.xinqushi.utils.MyDateUtils;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.*;

/**
 * @author xjie 2019/8/9 17:05
 * @description
 */
public class Test {
    private static volatile ThreadPoolExecutor executor;

    private static Executor getExecutor(){
        if(executor == null){
            synchronized (Test.class){
                System.out.println("executor start ----"+ MyDateUtils.getString2Date(new Date(),MyDateUtils.yyyyMMddTHHmmss));
                executor = new ThreadPoolExecutor(1, 1,
                        10L, TimeUnit.SECONDS,
                        new LinkedBlockingQueue<Runnable>(),
                        new ThreadFactory() {
                            public Thread newThread(Runnable r) {
                                return new Thread(r, "nyjh-delete-file-"+ MyDateUtils.getString2Date(new Date(),MyDateUtils.yyyyMMddTHHmmss));
                            }
                        });
                executor.allowCoreThreadTimeOut(true);
            }
        }
        return executor;
    }

    public static void main(String[] args) {
        getExecutor();
        executor.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + MyDateUtils.getString2Date(new Date(),MyDateUtils.yyyyMMddTHHmmss));
                try {
                    Thread.sleep(1000L);//1S
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + MyDateUtils.getString2Date(new Date(),MyDateUtils.yyyyMMddTHHmmss));
            }
        });
        new Thread(()->{
            while (true){
                try {
                    Thread.sleep(20000L);
                    new Thread(()->{
                        while (true){
                            try {
                                Thread.sleep(1000L);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            executor.execute(()->{
                                System.out.println(Thread.currentThread().getName());
                            });
                        }
                    }).start();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
